<template>
  <div class="notification-settings">
    <h3>通知设置</h3>
    
    <el-form :model="notificationForm" label-width="200px" class="settings-form">
      <h4>通知渠道设置</h4>
      
      <el-form-item label="启用站内通知">
        <el-switch v-model="notificationForm.enableInApp"></el-switch>
      </el-form-item>
      
      <el-form-item label="启用邮件通知">
        <el-switch v-model="notificationForm.enableEmail"></el-switch>
      </el-form-item>
      
      <el-form-item v-if="notificationForm.enableEmail" label="邮件服务器">
        <el-input v-model="notificationForm.emailServer" placeholder="SMTP服务器地址"></el-input>
      </el-form-item>
      
      <el-form-item v-if="notificationForm.enableEmail" label="邮件端口">
        <el-input-number v-model="notificationForm.emailPort" :min="1" :max="65535"></el-input-number>
      </el-form-item>
      
      <el-form-item v-if="notificationForm.enableEmail" label="邮件账号">
        <el-input v-model="notificationForm.emailUsername" placeholder="邮箱账号"></el-input>
      </el-form-item>
      
      <el-form-item v-if="notificationForm.enableEmail" label="邮件密码">
        <el-input v-model="notificationForm.emailPassword" type="password" placeholder="邮箱密码或授权码"></el-input>
      </el-form-item>
      
      <el-form-item v-if="notificationForm.enableEmail" label="发件人">
        <el-input v-model="notificationForm.emailSender" placeholder="发件人邮箱"></el-input>
      </el-form-item>
      
      <el-form-item v-if="notificationForm.enableEmail" label="启用SSL/TLS">
        <el-switch v-model="notificationForm.emailUseSsl"></el-switch>
      </el-form-item>
      
      <el-form-item v-if="notificationForm.enableEmail">
        <el-button @click="testEmailConnection" :loading="testing">测试邮件连接</el-button>
      </el-form-item>
      
      <h4>通知频率设置</h4>
      
      <el-form-item label="文档更新立即通知">
        <el-switch v-model="notificationForm.instantNotification"></el-switch>
        <div class="form-tip">关闭后将按照下面的批量通知频率发送</div>
      </el-form-item>
      
      <el-form-item label="批量通知频率">
        <el-select v-model="notificationForm.batchFrequency">
          <el-option label="实时通知" value="realtime"></el-option>
          <el-option label="每小时通知" value="hourly"></el-option>
          <el-option label="每天通知" value="daily"></el-option>
          <el-option label="每周通知" value="weekly"></el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item v-if="notificationForm.batchFrequency === 'daily'" label="每天通知时间">
        <el-time-picker v-model="notificationForm.dailyNotificationTime" format="HH:mm"></el-time-picker>
      </el-form-item>
      
      <el-form-item v-if="notificationForm.batchFrequency === 'weekly'" label="每周通知时间">
        <div class="weekly-picker">
          <el-select v-model="notificationForm.weeklyNotificationDay" style="width: 100px">
            <el-option label="周一" value="1"></el-option>
            <el-option label="周二" value="2"></el-option>
            <el-option label="周三" value="3"></el-option>
            <el-option label="周四" value="4"></el-option>
            <el-option label="周五" value="5"></el-option>
            <el-option label="周六" value="6"></el-option>
            <el-option label="周日" value="0"></el-option>
          </el-select>
          <el-time-picker v-model="notificationForm.weeklyNotificationTime" format="HH:mm"></el-time-picker>
        </div>
      </el-form-item>
      
      <h4>通知模板设置</h4>
      
      <el-form-item label="文档更新通知模板">
        <el-input 
          v-model="notificationForm.documentUpdateTemplate" 
          type="textarea" 
          rows="3" 
          placeholder="文档更新通知模板内容"
        ></el-input>
        <div class="form-tip">可用变量: {documentTitle}, {documentUrl}, {updateTime}, {username}</div>
      </el-form-item>
      
      <el-form-item label="新文档通知模板">
        <el-input 
          v-model="notificationForm.newDocumentTemplate" 
          type="textarea" 
          rows="3" 
          placeholder="新文档通知模板内容"
        ></el-input>
        <div class="form-tip">可用变量: {documentTitle}, {documentUrl}, {createTime}, {username}</div>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="saveSettings" :loading="saving">保存设置</el-button>
        <el-button @click="resetSettings">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

const saving = ref(false)
const testing = ref(false)

// 通知设置表单
const notificationForm = reactive({
  // 通知渠道
  enableInApp: true,
  enableEmail: true,
  emailServer: 'smtp.example.com',
  emailPort: 465,
  emailUsername: 'notification@example.com',
  emailPassword: '',
  emailSender: 'Doc Subscribe System <notification@example.com>',
  emailUseSsl: true,
  
  // 通知频率
  instantNotification: true,
  batchFrequency: 'daily',
  dailyNotificationTime: new Date(2023, 0, 1, 9, 0),
  weeklyNotificationDay: '1',
  weeklyNotificationTime: new Date(2023, 0, 1, 9, 0),
  
  // 通知模板
  documentUpdateTemplate: '您订阅的文档 "{documentTitle}" 已更新，点击查看：{documentUrl}',
  newDocumentTemplate: '您订阅的分类或标签下有新文档 "{documentTitle}"，点击查看：{documentUrl}'
})

// 初始设置
const initialSettings = { ...notificationForm }

// 初始化
onMounted(async () => {
  await fetchSettings()
})

// 获取通知设置
async function fetchSettings() {
  try {
    // 这里替换为实际的API调用
    // const response = await axios.get('/api/admin/settings/notification')
    // Object.assign(notificationForm, response.data)
    
    // 模拟加载设置
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 保存初始设置（用于重置功能）
    Object.assign(initialSettings, JSON.parse(JSON.stringify(notificationForm)))
  } catch (error) {
    console.error('Failed to fetch notification settings:', error)
    ElMessage.error('加载通知设置失败')
  }
}

// 保存设置
async function saveSettings() {
  saving.value = true
  try {
    // 这里替换为实际的API调用
    // await axios.put('/api/admin/settings/notification', notificationForm)
    
    // 模拟保存
    await new Promise(resolve => setTimeout(resolve, 800))
    
    ElMessage.success('通知设置保存成功')
    
    // 更新初始设置
    Object.assign(initialSettings, JSON.parse(JSON.stringify(notificationForm)))
  } catch (error) {
    console.error('Failed to save notification settings:', error)
    ElMessage.error('保存通知设置失败')
  } finally {
    saving.value = false
  }
}

// 重置设置
function resetSettings() {
  Object.assign(notificationForm, JSON.parse(JSON.stringify(initialSettings)))
  ElMessage.info('已重置为上次保存的设置')
}

// 测试邮件连接
async function testEmailConnection() {
  if (!notificationForm.emailServer || !notificationForm.emailUsername) {
    ElMessage.warning('请先填写邮件服务器信息')
    return
  }
  
  testing.value = true
  try {
    // 这里替换为实际的API调用
    // await axios.post('/api/admin/settings/notification/test-email', {
    //   server: notificationForm.emailServer,
    //   port: notificationForm.emailPort,
    //   username: notificationForm.emailUsername,
    //   password: notificationForm.emailPassword,
    //   sender: notificationForm.emailSender,
    //   useSsl: notificationForm.emailUseSsl
    // })
    
    // 模拟测试
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    ElMessage.success('邮件连接测试成功')
  } catch (error) {
    console.error('Failed to test email connection:', error)
    ElMessage.error('邮件连接测试失败')
  } finally {
    testing.value = false
  }
}
</script>

<style scoped>
.notification-settings {
  padding: 10px;
}

h3, h4 {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

h4 {
  margin-top: 30px;
  color: #606266;
}

.settings-form {
  max-width: 800px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
  margin-top: 5px;
}

.weekly-picker {
  display: flex;
  gap: 10px;
  align-items: center;
}
</style> 